//
//  hvMapCustomCalloutAnnotationView.m
//  hvMapCustomCalloutAnnotationView
//
//  Created by moon on 14-5-7.
//  Copyright (c) 2014年 hv. All rights reserved.
//

#import "hvMapCustomCalloutAnnotationView.h"

@interface hvMapCustomCalloutAnnotationView()

@end

@implementation hvMapCustomCalloutAnnotationView
- (id)initWithAnnotation:(id<MKAnnotation>)annotation reuseIdentifier:(NSString *)reuseIdentifier{
	if(self=[super initWithAnnotation:annotation reuseIdentifier:reuseIdentifier]){
		self.canShowCallout = NO;
		
		_calloutView = [[hvArrowContainerView alloc] initWithFrame:CGRectZero];
		_calloutView.borderColor = [UIColor grayColor];
		_calloutView.borderWidth = 1;
		_calloutView.backgroundColor = [UIColor whiteColor];
		_calloutView.supportedArrowDirections = UIPopoverArrowDirectionDown;
		
		//內容視圖,用button的目的是實現點擊效果
		UIButton *contentButtonView = [UIButton buttonWithType:UIButtonTypeCustom];
		[contentButtonView addTarget:self action:@selector(contentViewDidTap:) forControlEvents:UIControlEventTouchUpInside];
		[contentButtonView addTarget:self action:@selector(contentViewDidTouchDown:) forControlEvents:UIControlEventTouchDown];
		[contentButtonView addTarget:self action:@selector(contentViewDidTouchUp:) forControlEvents:UIControlEventTouchUpOutside];
		_contentView = contentButtonView;
		
		_calloutView.contentView = _contentView;
		
		self.showsTouchWhenHighlighted = NO;
		self.highlightedColor = [UIColor grayColor];
		self.normalColor = [UIColor whiteColor];
	}
	return self;
}
- (void)contentViewDidTap:(UIButton *)sender{
	[self contentViewDidTouchUp:sender];
	if(self.calloutViewClickHandler){
		self.calloutViewClickHandler(self);
	}
	if (!self.showsTouchWhenHighlighted&&!self.calloutViewClickHandler) {
		[[self mapView] deselectAnnotation:self.annotation animated:YES];
	}
}
- (MKMapView *)mapView{
	UIView *outerView = self.superview;
	while (outerView!=nil) {
		if([outerView isKindOfClass:[MKMapView class]]){
			return (MKMapView *)outerView;
		}else{
			outerView = outerView.superview;
		}
	}
	return nil;
}
- (void)contentViewDidTouchDown:(UIButton *)button{
	if(self.showsTouchWhenHighlighted){
		self.calloutView.backgroundColor = self.highlightedColor;
		[self refreshCalloutView];
	}
}
- (void)contentViewDidTouchUp:(UIButton *)button{
	if (self.showsTouchWhenHighlighted) {
		self.calloutView.backgroundColor = [UIColor whiteColor];
		[self refreshCalloutView];
	}
}
- (void)setCalloutViewClickHandler:(AnnotationCalloutViewClickHandler)calloutViewClickHandler{
	_calloutViewClickHandler = [calloutViewClickHandler copy];
}

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event{
	BOOL inside = [super pointInside:point withEvent:event];
	if(!inside){
		//判斷是否點擊了彈出框
		if(self.calloutView.superview){
			CGPoint pointInCalloutView = [self convertPoint:point toView:self.calloutView];
			inside = [self.calloutView pointInside:pointInCalloutView withEvent:event];
		}
	}
	return inside;
}
- (void)setSelected:(BOOL)selected{
	[self setSelected:selected animated:NO];
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated{
	[super setSelected:selected];
	NSTimeInterval duration = 0.2;
	if (selected) {
		if(!self.calloutView.superview){
			[self refreshCalloutView];
			if(animated){
				[self addSubview:self.calloutView];
				[[self mapView] setRegion:[self adjustMapViewRegion] animated:animated];
				
				CGPoint point = self.calloutView.arrowPoint;
				CGRect startFrame = (CGRect){[self convertPoint:point fromView:self.calloutView],CGSizeZero};
				UIImageView *tmpImageView = [[UIImageView alloc] initWithFrame:startFrame];
				tmpImageView.image = [self imageSpotWithCalloutView];
				[self addSubview:tmpImageView];
				self.calloutView.hidden = YES;
				[UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
					tmpImageView.frame = self.calloutView.frame;
				} completion:^(BOOL finished) {
					[tmpImageView removeFromSuperview];
					self.calloutView.hidden = NO;
				}];
			}else{
				[self addSubview:self.calloutView];
				[[self mapView] setRegion:[self adjustMapViewRegion] animated:animated];
			}
		}
	}else{
		if(self.calloutView.superview){
			if(animated){
				CGPoint point = self.calloutView.arrowPoint;
				CGRect endFrame = (CGRect){[self convertPoint:point fromView:self.calloutView],CGSizeZero};
				UIImageView *tmpImageView = [[UIImageView alloc] initWithFrame:self.calloutView.frame];
				tmpImageView.image = [self imageSpotWithCalloutView];
				[self.calloutView removeFromSuperview];
				[self addSubview:tmpImageView];
				
				[UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
					tmpImageView.frame = endFrame;
				} completion:^(BOOL finished) {
					[tmpImageView removeFromSuperview];
				}];
			}else{
				[self.calloutView removeFromSuperview];
			}
		}
	}
}

/**
 *	獲取彈出框的截圖,用於動畫
 */
- (UIImage *)imageSpotWithCalloutView{
	UIGraphicsBeginImageContext(self.calloutView.bounds.size);
    [self.calloutView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
	return viewImage;
}
/**
 *	刷新彈出框
 */
- (void)refreshCalloutView{
	MKMapView *mapView = self.mapView;
	CGRect anchorRect = self.bounds;
	//self.calloutOffset默認值為(-8,0),即使設置了self.image值,因此如果出現箭頭
	anchorRect.origin.x += self.calloutOffset.x;
	anchorRect.origin.y += self.calloutOffset.y;
	
	//進行顯示區域的微調
	CGRect displayArea = [mapView convertRect:mapView.bounds toView:self];
	CGFloat space = 10;	//邊距
	displayArea = CGRectInset(displayArea, space, space);
	displayArea.origin.y = -NSIntegerMax/2;
	displayArea.size.height = NSIntegerMax;
	
	CGRect frameInMap = self.frame;
	CGRect mapViewBounds = mapView.bounds;
	if(CGRectGetMinX(frameInMap)-space<CGRectGetMinX(mapViewBounds)){
		displayArea.origin.x -= CGRectGetMinX(mapViewBounds)-CGRectGetMinX(frameInMap)+space;
	}else if(CGRectGetMaxX(frameInMap)+space>CGRectGetMaxX(mapViewBounds)){
		displayArea.origin.x += CGRectGetMaxX(frameInMap)+space-CGRectGetMaxX(mapViewBounds);
	}

	_calloutView.anchorRect = anchorRect;
	_calloutView.displayArea = displayArea;
	[_calloutView refresh];
}

/**
 *	調整外層mapview的顯示region,使得彈出框全部顯示
 */
- (MKCoordinateRegion)adjustMapViewRegion{
	MKMapView *mapView = [self mapView];
	CGRect calloutViewFrameInMap = [mapView convertRect:_calloutView.frame fromView:self];
	CGRect mapViewBounds = mapView.bounds;
	MKCoordinateRegion region = mapView.region;
	MKCoordinateRegion deta;
	CGFloat space = 10;	//邊距
	if(CGRectGetMinX(calloutViewFrameInMap)<CGRectGetMinX(mapViewBounds)){
		deta = [mapView convertRect:CGRectMake(0, 0, space+CGRectGetMinX(mapViewBounds)-CGRectGetMinX(calloutViewFrameInMap), 1) toRegionFromView:self];
		region.center.longitude -= deta.span.longitudeDelta;
	}else if(CGRectGetMaxX(calloutViewFrameInMap)>CGRectGetMaxX(mapViewBounds)){
		deta = [mapView convertRect:CGRectMake(0, 0, space+CGRectGetMaxX(calloutViewFrameInMap)-CGRectGetMaxX(mapViewBounds), 1) toRegionFromView:self];
		region.center.longitude += deta.span.longitudeDelta;
	}
	if(CGRectGetMinY(calloutViewFrameInMap)<CGRectGetMinY(mapViewBounds)){
		deta = [mapView convertRect:CGRectMake(0, 0, 1,space+CGRectGetMinY(mapViewBounds)-CGRectGetMinY(calloutViewFrameInMap)) toRegionFromView:self];
		region.center.latitude += deta.span.latitudeDelta;
	}else if(CGRectGetMaxY(calloutViewFrameInMap)>CGRectGetMaxY(mapViewBounds)){
		deta = [mapView convertRect:CGRectMake(0, 0, 1,space+CGRectGetMaxY(calloutViewFrameInMap)-CGRectGetMaxY(mapViewBounds)) toRegionFromView:self];
		region.center.latitude -= deta.span.latitudeDelta;
	}
	return region;
}
@end
